package com.rescue.controller.notify;

import com.rescue.constant.MessageConstant;
import com.rescue.result.Result;
import com.rescue.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RequestMapping("/common")
@RestController
@Api(tags = "通用接口")
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    @ApiOperation("上传图片到阿里云OSS")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传，文件名：" + file.getOriginalFilename());
        String originalFilename = file.getOriginalFilename();//原始文件名
        String expandedName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //构造新文件名
        String newName = UUID.randomUUID().toString() + expandedName;
        String url = null;
        try {
            url = aliOssUtil.upload(file.getBytes(), newName);
            log.info("文件上传成功，文件访问URL：{}", url);
            return Result.success(url);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("文件上传失败");
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
